package com.tom.learnhigher.tools;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ReflectUtil;
import com.tom.contants.Contants;
import com.tom.learnbase.two.ChatMemoryTest;
import dev.langchain4j.agent.tool.Tool;
import dev.langchain4j.agent.tool.ToolSpecification;
import dev.langchain4j.agent.tool.ToolSpecifications;
import dev.langchain4j.data.message.AiMessage;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.memory.ChatMemory;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import dev.langchain4j.model.output.Response;
import dev.langchain4j.service.AiServices;
import dev.langchain4j.store.memory.chat.InMemoryChatMemoryStore;
import org.junit.jupiter.api.Test;

/**
 * OpenAiChatModel
 * AzureOpenAiChatModel
 * LocalAiChatModel
 * QianfanChatModel
 * 支持工具或者函数调用，其他的不一定支持
 *
 * 底层逻辑是：generate(List<ChatMessage>, List<ToolSpecification>)  ToolSpecification 创建多个工具，模型会匹配选择使用那个工具
 *
 *
 *@Tool 有两个属性 name :工具的名称。如果没有提供，方法的名称将作为工具的名称。  value :工具的描述。
 *
 *
 */
public class ToolsTest {


    interface MathGenius {

        String ask(String question);
    }

    class Calculator {

        @Tool
        public double add(int a, int b) {
            return a + b;
        }

        @Tool
        public double squareRoot(double x) {
            return Math.sqrt(x);
        }
    }
    @Test
    public void TestTo1(){
        ChatMemory chatMemory = MessageWindowChatMemory.builder()
                .maxMessages(10)
                .chatMemoryStore(new InMemoryChatMemoryStore())
                .build();

        MathGenius mathGenius = AiServices.builder(MathGenius.class)
                .chatLanguageModel(Contants.openAiChatModellog)
                .tools(new Calculator())
                .chatMemory(chatMemory)
                .build();

        String answer = mathGenius.ask("What is the square root of 475695037565?");

        System.out.println(answer); // The square root of 475695037565 is 689706.486532.
    }


    /**
     * 手动创建
     */
    @Test
    public void test2(){
        ToolSpecification add = ToolSpecifications.toolSpecificationFrom(ReflectUtil.getMethodByName(Calculator.class,"add"));
        ToolSpecification squareRoot = ToolSpecifications.toolSpecificationFrom(ReflectUtil.getMethodByName(Calculator.class,"squareRoot"));

        ChatMessage chatMessage = UserMessage.userMessage("What is the square root of 475695037565?");
        Response<AiMessage> generate = Contants.openAiChatModellog.generate(ListUtil.toList(chatMessage), ListUtil.toList(add, squareRoot));

        System.out.println(chatMessage.text());


    }
}
